package cn.com.taiji.oospub.wechat.controller.order;

import cn.com.taiji.manager.ManagerException;
import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.Finals;
import cn.com.taiji.oospub.wechat.common.HisAddressUtil;
import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.OrderSend;
import cn.com.taiji.oospub.wechat.common.tool.DoubleTools;
import cn.com.taiji.oospub.wechat.common.tool.NumberTools;
import cn.com.taiji.oospub.wechat.common.tool.SmallTicketPrinter;
import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.common.util.JsonUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.common.RandomStringGenerator;
import cn.com.taiji.oospub.wechat.common.wxpay.common.XMLParser;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.Signature;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.UnifiedorderService;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.WxPaySendData;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.model.MemberBaseInfoModel;
import cn.com.taiji.oospub.wechat.service.*;
import cn.com.taiji.pub.StringTools;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.com.taiji.oospub.wechat.entity.CoursesOrders.CoursesOrderStatus.DDYWC;
import static cn.com.taiji.oospub.wechat.entity.CoursesOrders.CoursesOrderStatus.WCTK;

/**
 * 订单
 *
 * @author fan
 */
@Controller
@RequestMapping("/wx/order")
public class OrderController extends BaseLogController {

    @Value("${kongxc_pos_http_server_url}")
    private String kongxc_pos_http_server_url;
    @Value("${kongxc_wx_diancan_orderServlet}")
    public String kongxc_wx_diancan_orderServlet;
    @Value("${PROPASS}")
    public String PROPASS;
    @Value("${CUS_NAME}")
    public String CUS_NAME;
    @Value("${appID}")
    public String appID;
    @Value("${appsecret}")
    public String appSecret;
    @Value("${chuzhika_num}")
    private String chuzhika_num;
    @Value("${chuzhika_faFang}")
    private String chuzhika_faFang;
    @Value("${REFUND_URL}")
    private String refundUrl;


    @Autowired
    private ICoursesOrdersService coursesOrdersManager;
    @Autowired
    private ICoursesOrdersDetailsService coursesOrdersDetailsManager;
    @Autowired
    private ICoursesService coursesService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private ICourseNutritionService courseNutritionService;
    @Autowired
    private IOrderCommentService orderCommentService;
    @Autowired
    private ICoursesImgService coursesImgService;
    @Autowired
    private IOrderOfDaynutService orderOfDaynutService;
    @Autowired
    private IOrderCodeService orderCodeService;
    @Autowired
    private IMealTimeService mealTimeService;
    @Autowired
    private IDiancanSchoolurlService diancanSchoolurlService;
    @Autowired
    private IOrderDetailInfoService orderDetailInfoService;
    @Autowired
    private UnifiedorderService unifiedorderService;
    @Autowired
    private Signature signature;
    @Autowired
    private IReceiveAddressService receiveAddressService;
    @Autowired
    private SmallTicketPrinter smallTicketPrinter;
    @Autowired
    private IRestaurantMealTimeService restaurantMealTimeService;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private IAccesstokensaveService accesstokensaveService;
    @Autowired
    private OrderSend orderSend;
    @Autowired
    private ICustomerMinMumService customerMinMumService;
    @Autowired
    private IMemberAllowanceUseHistoryService memberAllowanceUseHistoryService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private HisAddressUtil hisAddressUtil;

    /**
     * 增加临时订单明细
     *
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getJia", method = RequestMethod.POST)
    @ResponseBody
    public synchronized String getJia(@RequestParam("id") String id, Model model, HttpServletRequest request,
                                      HttpServletResponse response) throws IOException {
        try {
            model.addAttribute("result", "success");
            model.addAttribute("message", "点餐成功");
            MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
            //查询菜品
            Courses courses = coursesService.findById(id);

            //菜品剩余数量不足
            if (courses.getRemainCount() < 1) {
                model.addAttribute("result", false);
                model.addAttribute("message", "该菜品已售空");
                return JSONObject.toJSONString(model);
            }
            //获取菜品类别
            String lb = courses.getType().toString();

            //验证菜品是否售卖
            QueryWrapper<MealTime> mealTimeModels = new QueryWrapper<>();
            mealTimeModels.eq("mealType", courses.getType());
            mealTimeModels.eq("school_id", member.getSchoolId());
            mealTimeModels.eq("code", courses.getMealTimeCode().toString());
            mealTimeModels.orderByAsc("sort_no");
            //菜品售卖时间
            MealTime mealTime = mealTimeService.getOne(mealTimeModels, false);
            //当前时间
            if (courses.getEndTime().isBefore(LocalDateTime.of(LocalDate.now(), LocalTime.MAX))) {
                //菜品为今日销售菜品
                if (LocalTime.now().isAfter(mealTime.getDCendTime().toLocalTime())) {
                    //菜品销售已结束
                    model.addAttribute("result", false);
                    model.addAttribute("message", "该菜品今日已结束销售");
                    return JSONObject.toJSONString(model);
                }
            }

            String remark = request.getParameter("remark");
            if (remark == null) {
                remark = "";
            }
            if (StringUtils.hasText(remark) && remark.endsWith(",")) {
                remark = remark.substring(0, remark.length() - 1);
            }
            if (courses.getIsStop().equals("0")) {
                //该菜品未停售
                QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
                queryModel.eq("is_effective", false);
                queryModel.eq("creator", member.getId());
                queryModel.ge("last_changed", LocalDate.now());
                queryModel.eq("lb", lb);
                List<CoursesOrdersDetails> detailsList = coursesOrdersDetailsManager.queryList(queryModel);
//                List<CoursesOrdersDetails> collect = detailsList.stream().filter(i -> !i.getMealCode().equals(courses.getMealTimeCode())).collect(Collectors.toList());
                if (detailsList.stream().filter(i -> !i.getMealCode().equals(courses.getMealTimeCode())).count() > 0) {
                    //含有不同餐次菜品订单
                    model.addAttribute("result", false);
                    model.addAttribute("message", "不同餐次不能同时下单");
                    return JSONObject.toJSONString(model);
                } else if (detailsList.size() > 0 && !detailsList.get(0).getCourse().getStartTime().toLocalDate().equals(courses.getStartTime().toLocalDate())) {
                    model.addAttribute("result", false);
                    model.addAttribute("message", "不是同一天餐品不能同时下单,请先结算之前订单");
                    return JSONObject.toJSONString(model);
                } else {
                    queryModel.eq("course_id", courses.getId());
                    queryModel.eq("remark", remark == null ? "" : remark);
                    detailsList = coursesOrdersDetailsManager.queryList(queryModel);
                    if (detailsList.size() > 0) {
                        CoursesOrdersDetails oldDetail = detailsList.get(0);
                        oldDetail.setQuantity(oldDetail.getQuantity() + 1.0);
                        courses.setRemainCount(courses.getRemainCount() - 1.0);
                        coursesService.updateById(courses);
                        coursesOrdersDetailsManager.updateById(oldDetail);
                        model.addAttribute("ordersDetails", oldDetail);
                    } else {
                        CoursesOrdersDetails cod = new CoursesOrdersDetails();
                        cod.setMealCode(courses.getMealTimeCode());
                        cod.setMealName(courses.getMealName());
                        cod.setLb(Finals.MealType.valueOf(lb));
                        cod.setPrice(courses.getPrice());
                        cod.setCourseId(id);
                        cod.setQuantity(1.0);
                        cod.setCreator(member.getId());
                        cod.setLastChanged(LocalDateTime.of(courses.getStartTime().toLocalDate(), LocalTime.now()));
                        cod.setIsEffective(false);
                        cod.setIsRefunding(0);
                        cod.setRemark(remark);
                        courses.setRemainCount(courses.getRemainCount() - 1.0);
                        coursesService.updateById(courses);
                        coursesOrdersDetailsManager.save(cod);
                        model.addAttribute("ordersDetails", cod);
                    }
                }
            } else {
                //菜品已停售
                QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
                queryModel.eq("course_id", courses.getId());
                queryModel.eq("is_effective", false);
                queryModel.eq("creator", member.getId());
                List<CoursesOrdersDetails> detailsList = coursesOrdersDetailsManager.list(queryModel);
                if (null != detailsList && detailsList.size() > 0) {
                    coursesOrdersDetailsManager.removeByIds(detailsList);
                }
                model.addAttribute("result", false);
                model.addAttribute("message", "该菜品已售完");
                return JSONObject.toJSONString(model);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String nutrientStr = "{\"sucOrFai\":\"fail\",\"message\":\"" + e.getMessage() + "\"}";
            return JSONObject.toJSONString(nutrientStr);
        }
        return JSONObject.toJSONString(model);
    }


    /**
     * 减少临时订单明细
     *
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getJian", method = RequestMethod.POST)
    @ResponseBody
    public synchronized String getJian(@RequestParam("id") String id, Model model, HttpServletRequest request,
                                       HttpServletResponse response) throws IOException {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String remark = request.getParameter("remark");
        Courses courses = coursesService.findById(id);
        QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
        queryModel.eq("course_id", courses.getId());
        queryModel.eq("is_effective", false);
        queryModel.eq("creator", member.getId());
        queryModel.eq("remark", remark == null ? "" : remark);
        List<CoursesOrdersDetails> detailsList = coursesOrdersDetailsManager.queryList(queryModel);
        if (null != detailsList && detailsList.size() > 0) {
            CoursesOrdersDetails oldDetail = detailsList.get(0);
            Double quantity = oldDetail.getQuantity();
            if (quantity > 1.0) {
                oldDetail.setQuantity(quantity - 1.0);
                coursesOrdersDetailsManager.updateById(oldDetail);
            } else {
                coursesOrdersDetailsManager.removeById(oldDetail.getId());
            }

            model.addAttribute("ordersDetails", oldDetail);
        }
        return JSONObject.toJSONString(model);
    }


    @GetMapping("/emptyShoppingCart")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public String emptyShoppingCart(Map<String, Object> result, HttpServletRequest request) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        List<CoursesOrdersDetails> courseOrdersDetailsList = coursesOrdersDetailsManager.query().eq("creator", member.getId())
                .eq("is_effective", false).list();
        if (courseOrdersDetailsList.size() > 0) {
            boolean res = coursesOrdersDetailsManager.removeByIds(courseOrdersDetailsList.stream().map(CoursesOrdersDetails::getId).collect(Collectors.toList()));
            if (res) {
                result.put("result", "success");
                result.put("message", "清空购物车成功");
            } else {
                result.put("result", "fail");
                result.put("message", "清空购物车失败");
            }
        } else {
            result.put("result", "success");
            result.put("message", "清空购物车成功");
        }
        return JSONObject.toJSONString(result);
    }


    /**
     * 再来一单
     *
     * @param request
     * @param response
     * @param model
     * @throws IOException
     */
//    @RequestMapping(value = "/copyOrder", method = RequestMethod.POST)
//    @ResponseBody
    public String copyOrder(@RequestParam String orderId, Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        CoursesOrders mainOrder = coursesOrdersManager.getById(orderId);

        //当前时间
        LocalTime nowTime = LocalTime.now();

        LocalDateTime nowDateTime = LocalDateTime.now();

        List<CoursesOrdersDetails> coursesOrdersDetails = coursesOrdersDetailsManager.findByProperty("order_id", mainOrder.getId());

        for (CoursesOrdersDetails courseOrder : coursesOrdersDetails) {
            courseOrder.setIsEffective(false);
            courseOrder.setId(null);
            courseOrder.setOrderId(null);
            courseOrder.setLastChanged(LocalDateTime.now());
            courseOrder.setRemark("");
            courseOrder.setIsRefunding(0);
            //查看菜品今日是否售卖
            Courses courses = coursesService.findById(courseOrder.getCourseId());
            QueryWrapper<Courses> coursesWrapper = new QueryWrapper<>();
            coursesWrapper.ge("startTime", LocalDate.now());
            coursesWrapper.le("endTime", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
            coursesWrapper.and(i -> i.eq("name_ch", courses.getNameCh()).or().eq("name_en", courses.getNameEn()));
            Courses one = coursesService.getOne(coursesWrapper, false);
            if (one != null) {
                //该菜品今日在售
                QueryWrapper<MealTime> mealTimeWrapper = new QueryWrapper<>();
                mealTimeWrapper.eq("code", one.getMealTimeCode());
                mealTimeWrapper.eq("mealType", one.getType());
                mealTimeWrapper.eq("school_id", member.getSchoolId());
                MealTime mealTime = mealTimeService.getOne(mealTimeWrapper, false);
                if (mealTime.getDCstartTime().toLocalTime().isAfter(nowTime) || mealTime.getDCendTime().toLocalTime().isBefore(nowTime)) {
                    //今日已结束销售或未开始销售
                    courseOrder.setIsEffective(false);
                    continue;
                }
            } else {
                courseOrder.setQuantity(0.0);
                continue;
            }
            if (courses.getRemainCount() <= courseOrder.getQuantity()) {
                courseOrder.setQuantity(courses.getRemainCount());
                courses.setRemainCount(0.0);
            } else {
                courses.setRemainCount(courses.getRemainCount() - courseOrder.getQuantity());
            }

            coursesService.updateById(courses);
        }
        coursesOrdersDetailsManager.saveBatch(coursesOrdersDetails);
        model.addAttribute("result", "success");
        model.addAttribute("orderList", coursesOrdersDetails);
        return JSONObject.toJSONString(model);
    }


    /**
     * 查询临时订单明细
     *
     * @param lb
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getLsOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public String getLsOrderDetail(@RequestParam String lb, Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", member.getId());
        detailModel.ge("last_changed", LocalDate.now());
        detailModel.in("lb", lb, "dcwm");
        List<CoursesOrdersDetails> lsList = coursesOrdersDetailsManager.queryList(detailModel);
        if (lsList.size() <= 0) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "暂无订单");
            return JSONObject.toJSONString(model);
        }
        Courses courses = null;

        Double totalAmount = 0.0;
        for (CoursesOrdersDetails coursesOrdersDetails : lsList) {
            totalAmount += coursesOrdersDetails.getQuantity() * coursesOrdersDetails.getPrice();
            coursesOrdersDetails.setQuantityStr(String.valueOf(coursesOrdersDetails.getQuantity()));
            coursesOrdersDetails.setPriceStr(coursesOrdersDetails.getPrice() * coursesOrdersDetails.getQuantity() + "");
            courses = coursesOrdersDetails.getCourse();
            //--------查询菜品主图开始----------
            QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
            coursesImgModel.eq("course_pos_no", courses.getPosNo());
            coursesImgModel.isNotNull("img_path");
            coursesImgModel.isNotNull("img_url");
            coursesImgModel.orderByDesc("mainImg");
            List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
            if (coursesImgList != null && coursesImgList.size() > 0) {
                coursesOrdersDetails.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
            if (StringUtils.hasText(coursesOrdersDetails.getRemark())) {
                coursesOrdersDetails.setCourseName(courses.getNameCh() + "(" + coursesOrdersDetails.getRemark() + ")");
                coursesOrdersDetails.setCourseNameEn(courses.getNameEn() + "(" + coursesOrdersDetails.getRemark() + ")");
            } else {
                coursesOrdersDetails.setCourseName(courses.getNameCh());
                coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
            }
        }
        //查询取餐时间
        MealTime qcTime = mealTimeService.query().eq("code", courses.getMealTimeCode())
                .eq("mealType", courses.getType()).eq("school_id", courses.getSchoolId()).one();
        MemberAllowanceUseHistory memberAllowanceUseHistory = memberAllowanceUseHistoryService.query().eq("member_id", member.getId())
                .eq("use_time", courses.getStartTime().toLocalDate())
                .eq("meal_code", courses.getMealTimeCode()).one();
        CustomerMinMum customerMinMum = customerMinMumService.query().eq("customer_type_id", member.getCustomerType()).one();

        if ((memberAllowanceUseHistory == null || memberAllowanceUseHistory.getAllowanceAmount() > 0)
                && customerMinMum != null
                && (customerMinMum.getMorningAllowance() > 0 || customerMinMum.getAfternoonAllowance() > 0 || customerMinMum.getEveningAllowance() > 0)) {
            switch (courses.getMealTimeCode()) {
                case "01":
                    model.addAttribute("minimumConsumption", customerMinMum.getMorningMinMum());
                    if (memberAllowanceUseHistory == null) {
                        if (totalAmount <= customerMinMum.getMorningAllowance()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", customerMinMum.getMorningAllowance());
                        }
                    } else {
                        if (totalAmount <= memberAllowanceUseHistory.getAllowanceAmount()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", memberAllowanceUseHistory.getAllowanceAmount());
                        }
                    }
                    break;
                case "02":
                    model.addAttribute("minimumConsumption", customerMinMum.getAfternoonMinMum());
                    if (memberAllowanceUseHistory == null) {
                        if (totalAmount <= customerMinMum.getAfternoonAllowance()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", customerMinMum.getAfternoonAllowance());
                        }
                    } else {
                        if (totalAmount <= memberAllowanceUseHistory.getAllowanceAmount()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", memberAllowanceUseHistory.getAllowanceAmount());
                        }
                    }
                    break;
                case "03":
                    model.addAttribute("minimumConsumption", customerMinMum.getEvenningMinMum());
                    if (memberAllowanceUseHistory == null) {
                        if (totalAmount <= customerMinMum.getEveningAllowance()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", customerMinMum.getEveningAllowance());
                        }
                    } else {
                        if (totalAmount <= memberAllowanceUseHistory.getAllowanceAmount()) {
                            model.addAttribute("allowanceAmount", totalAmount);
                        } else {
                            model.addAttribute("allowanceAmount", memberAllowanceUseHistory.getAllowanceAmount());
                        }
                    }
                    break;
                default:
                    model.addAttribute("allowanceAmount", 0);
                    model.addAttribute("minimumConsumption", 0);
                    break;
            }
        } else {
            model.addAttribute("allowanceAmount", 0);
            model.addAttribute("minimumConsumption", 0);
        }
        model.addAttribute("result", "success");
        model.addAttribute("lsList", lsList);
        model.addAttribute("qcStartTime", qcTime.getQCstartTime().toLocalTime());
        model.addAttribute("qcEndTime", qcTime.getQCendTime().toLocalTime());
        LocalDate takeDate = courses.getStartTime().toLocalDate();
        String mealTimeCode = courses.getMealTimeCode();
        model.addAttribute("canToPay", true);
        if (takeDate.equals(LocalDate.now().plusDays(1))) {
            if (LocalTime.now().isAfter(LocalTime.of(19, 0, 0))) {
                //超出结算时间
                model.addAttribute("canToPay", false);
            }
        }
//        if (takeDate.isBefore(LocalDate.now().plusDays(2))) {
//            if (takeDate.equals(LocalDate.now())) {
//                if ((LocalTime.now().isAfter(LocalTime.of(10, 0, 0)) && "02".equals(mealTimeCode))
//                        || (LocalTime.now().isAfter(LocalTime.of(16, 0, 0)) && "03".equals(mealTimeCode))
//                        || ("01".equals(mealTimeCode))
//                ) {
//                    //超出当日结算时间
//                    model.addAttribute("canToPay", false);
//                }
//            } else {
//                if (LocalTime.now().isAfter(LocalTime.of(16, 0, 0)) && "01".equals(mealTimeCode)) {
//                    //超出结算时间
//                    model.addAttribute("canToPay", false);
//                }
//            }
//        }
//        if (takeDate.isBefore(LocalDate.now().plusDays(2))) {
//            if (takeDate.equals(LocalDate.now())) {
//                if ((LocalTime.now().isAfter(LocalTime.of(10, 0, 0)) && "02".equals(mealTimeCode))
//                        || (LocalTime.now().isAfter(LocalTime.of(16, 0, 0)) && "03".equals(mealTimeCode))
//                        || (LocalTime.now().isAfter(LocalTime.of(6, 30, 0)) && "01".equals(mealTimeCode))
//                ) {
//                    //超出当日结算时间
//                    model.addAttribute("canToPay", false);
//                }
//            }
//        }
//        model.addAttribute("peisong", member.getRestaurant().getDeliveryFee());
        model.addAttribute("peisong", 0);
        //项目可用支付方式
        model.addAttribute("payType", member.getSchool().getUseXj());
        //项目取餐方式
        model.addAttribute("takeMealType", member.getSchool().getTakeMealType());
        model.addAttribute("remark", "");
        if (StringUtils.hasText(member.getPatientNumber())) {
            String doctorsOrder = hisAddressUtil.getDoctorsOrder(member.getPatientNumber());
            if (StringUtils.hasText(doctorsOrder)) {
                model.addAttribute("remark", "医生建议:" + doctorsOrder + "\r\n");
            }
        }
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(CoursesOrdersDetails.class, "price", "imageMainPath", "courseId", "priceStr", "id", "courseName", "courseNameEn", "quantity");
        return JSONObject.toJSONString(model, filter);
    }


    /**
     * 去付款
     *
     * @param totalMoney
     * @param model
     * @param request
     * @param response
     * @throws ManagerException
     * @throws IOException
     */
    @RequestMapping(value = "/payOrder", method = RequestMethod.POST)
    public void payOrder(@RequestParam("totalMoney") Double totalMoney, Model model,
                         HttpServletRequest request, HttpServletResponse response) throws ManagerException, IOException {
        MemberBaseInfo memberInfo = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        HttpUtil send;
        ObjectToXML toXml;
        //获取access_token开始----------
        String accessToken = accesstokensaveService.query().one().getAccessToken();
        //-----获取access_token结束----------
        String type = request.getParameter("type");
        String orderType = request.getParameter("orderType");
        Double allowanceAmount = Double.valueOf(request.getParameter("allowanceAmount"));
        String takeMealType = "";
        if (orderType.equals("1")) {
            takeMealType = request.getParameter("takeMealType");
        }
        String remark = request.getParameter("remark");
        String lb = request.getParameter("lb");
        if (remark == null) {
            remark = "";
        }
        String address = request.getParameter("addressId");
        if (StringUtils.hasText(remark)) {
            remark = java.net.URLDecoder.decode(remark, "UTF-8");
//            model.addAttribute("remark", remark);
        }
        //创建订单主单
        CoursesOrders order = new CoursesOrders();
        order.setSchoolId(memberInfo.getSchoolId());
        order.setMemberId(memberInfo.getId());
        order.setPatientNumber(memberInfo.getPatientNumber());
        order.setOrderCode(orderCodeService.getNextCodes(memberInfo.getSchool().getCode(), "1", 1)[0]);
        order.setCreateTime(LocalDateTime.now());
        order.setAmount(totalMoney - allowanceAmount);
        order.setStatus(CoursesOrders.CoursesOrderStatus.WZF);//未支付
        order.setHasprint(CoursesOrders.HasPrint.WDY);
        order.setPayWay(CoursesOrders.PayWay.valueOf(type));
        order.setPayMemberName(memberInfo.getName());
//        if (StringUtils.hasText(memberInfo.getPatientNumber())) {
//            order.setRemark(remark + "HIS:" + hisAddressUtil.getDoctorsOrder(memberInfo.getPatientNumber()));
//        } else {
        order.setRemark(remark);
//        }
        order.setTakeMealType(takeMealType);//自提方式1,到店,2取餐柜,3,外卖
        order.setOrderType(orderType);//订单类型,1点餐,2外卖
        order.setTakeCode(new Double(Math.random() * 900000 + 100000).intValue() + "");
        if ("1".equals(takeMealType)) {
            order.setReceiveAddressId("admin");
            order.setTakeCode(order.getOrderCode().substring(18));
        } else {
            order.setReceiveAddressId(address);
        }
        order.setMobile(memberInfo.getMobile());
        ReceiveAddress receiveAddress = receiveAddressService.getById(order.getReceiveAddressId());
        order.setAddress(receiveAddress);
        order.setAddressDetail(receiveAddress.getAddress());
        order.setArchitecture(receiveAddress.getArchitecture());
        if ("3".equals(takeMealType)) {
            order.setPayMemberName(receiveAddress.getName());
            order.setMobile(receiveAddress.getTel());
        }
        //明细修改
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", memberInfo.getId());
        detailModel.in("lb", lb, "dcwm");
        detailModel.ge("last_changed", LocalDate.now());
        detailModel.gt("quantity", 0);
        List<CoursesOrdersDetails> detailList = coursesOrdersDetailsManager.queryList(detailModel);
        //订单取餐时间
        order.setTakeTime(LocalDateTime.of(detailList.get(0).getCourse().getStartTime().toLocalDate(), LocalTime.now()));
        order.setMealCode(detailList.get(0).getMealCode());
        order.setIdDelete("1");
        coursesOrdersManager.save(order);
        memberInfo.setAllowanceAmount(allowanceAmount);
        //判断支付方式
        //餐卡
        if (type.equals(CoursesOrders.PayWay.CK.toString())) {
            if (memberInfo.getAllowanceAmount() > 0) {
                CustomerMinMum customerMinMum = customerMinMumService.query().eq("customer_type_id", memberInfo.getCustomerType()).one();
                switch (order.getMealCode()) {
                    case "01":
                        memberInfo.setMaxAllowance(customerMinMum.getMorningAllowance());
                        break;
                    case "02":
                        memberInfo.setMaxAllowance(customerMinMum.getAfternoonAllowance());
                        break;
                    case "03":
                        memberInfo.setMaxAllowance(customerMinMum.getEveningAllowance());
                        break;
                    default:
                        memberInfo.setMaxAllowance(0.0);
                        break;
                }
            }
            String idNumber = memberInfo.getIdNumber();
            if (!StringUtils.hasText(idNumber)) {
                writeFailToBrowers("你还未关联餐卡信息，请联系管理员", response);
            } else {
                try {
                    String moneyType = request.getParameter("moneyType");
                    send = new HttpUtil(kongxc_pos_http_server_url);
                    toXml = new ObjectToXML();
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    String accountXml = toXml.requestAccountAllXMLKongxc(PROPASS, CUS_NAME, memberInfo.getSchool().getCode(), memberInfo.getIdNumber(), memberInfo.getZfPasswd(), uuid);
                    String responseAccountXml = null;
                    boolean isFail = false;
                    logger.info("oos request to pos start.query the account.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + memberInfo.getLoginName());
                    try {
                        responseAccountXml = send.sendToBoss(accountXml);

                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.debug(e.getMessage());
                        isFail = true;
                    }
                    if (!isFail) {
                        logger.info("pos responese oos end get the account.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + memberInfo.getLoginName());
                        String responseAccount = toXml.resolveReponseAccountXmlKongxc(responseAccountXml, request);
                        Double realAccount = 0.0;
                        if ("0000".equals(responseAccount)) {
                            String responseOrderXml = null;
                            List<MemberBaseInfoModel> accountList = toXml.resolveReponseAccountXml(responseAccountXml);
                            ArrayList<MemberBaseInfoModel> czAccountlist = new ArrayList<>();
                            ArrayList<MemberBaseInfoModel> bzAccountlist = new ArrayList<>();
                            if (accountList.size() > 0) {
                                for (MemberBaseInfoModel memberAccount : accountList) {
                                    if (chuzhika_num.equals(memberAccount.getAccountType())) {
                                        czAccountlist.add(memberAccount);
                                    } else if (chuzhika_faFang.equals(memberAccount.getAccountType())) {
                                        bzAccountlist.add(memberAccount);
                                    }
                                }
                            } else {
                                throw new ManagerException("该账号未开通账户或账户已过期");
                            }
                            if (bzAccountlist.size() > 0) {
                                //补助卡存在
                                for (MemberBaseInfoModel memberAccount : bzAccountlist) {
                                    //计算补助卡余额
                                    realAccount += (memberAccount.getAmount() == null ? 0.00d : memberAccount.getAmount());
                                }
                                Double BzRealAccount = realAccount;
                                if (BzRealAccount >= order.getAmount()) {
                                    //补助卡支付
//                                    if (memberInfo.getAllowanceAmount() > 0) {
//                                        responseOrderXml = payWithAllowanceAccount(request, totalMoney, chuzhika_faFang, memberInfo, order, detailList);
//                                    } else {
//                                        responseOrderXml = payWithBzAccount(request, memberInfo, order, detailList);
//                                    }
                                    responseOrderXml = payWithBzAccount(request, memberInfo, order, detailList);
                                } else {
                                    realAccount = 0.0;
                                    for (MemberBaseInfoModel memberAccount : czAccountlist) {
                                        //计算储值卡余额
                                        realAccount += (memberAccount.getAmount() == null ? 0.00d : memberAccount.getAmount());
                                    }
                                    if ((realAccount + BzRealAccount) >= order.getAmount() && BzRealAccount > 0) {
                                        //混合支付
                                        responseOrderXml = payWithBzAndCzAccount(request, BzRealAccount, memberInfo, order, detailList);
                                    } else if (realAccount < order.getAmount()) {
                                        //储值卡余额不足
                                        Double chajia = order.getAmount() - realAccount;
                                        String moneyStr = NumberTools.format2Decimal2Str(chajia);
                                        throw new ManagerException("支付失败，你的帐户余额为" + realAccount + ",不足以支付该订单,请最少充值【" + moneyStr + "】元才可以支付");
                                    } else {
                                        responseOrderXml = payWithStoreAccount(request, memberInfo, order, detailList);
                                    }
                                }
                            } else if (czAccountlist.size() > 0) {
                                //补助卡不存在,储值卡存在
                                for (MemberBaseInfoModel memberAccount : czAccountlist) {
                                    //计算储值卡余额
                                    realAccount += (memberAccount.getAmount() == null ? 0.00d : memberAccount.getAmount());
                                }
                                if (realAccount < order.getAmount()) {
                                    Double chajia = order.getAmount() - realAccount;
                                    String moneyStr = NumberTools.format2Decimal2Str(chajia);
                                    throw new ManagerException("支付失败，你的帐户余额为" + realAccount + ",不足以支付该订单,请最少充值【" + moneyStr + "】元才可以支付");
                                } else {
                                    //储值卡支付
                                    responseOrderXml = payWithStoreAccount(request, memberInfo, order, detailList);
                                }
                            } else {
                                throw new ManagerException("支付失败，该账号未开通账户");
                            }
                            //返回值判断
                            Document doc = null;
                            try {
                                doc = DocumentHelper.parseText(responseOrderXml);
                            } catch (DocumentException e) {
                                writeFailToBrowers("服务器异常", response);
                                e.printStackTrace();
                            }
                            //-------给pos 推送 订单数据结束-------
                            if (doc != null) {
                                String desc = toXml.responseDesc(responseOrderXml, request);
                                if (desc.equals("成功")) {
                                    //推送完成
                                    order.setIdDelete("0");
                                    coursesOrdersManager.updateById(order);
                                    orderReceiptPrint(detailList, order, response);
                                    for (CoursesOrdersDetails cod : detailList) {
                                        cod.setOrderId(order.getId());
                                        cod.setIsEffective(true);
                                        coursesOrdersDetailsManager.updateById(cod);
                                    }
                                    Double chajia = realAccount - order.getAmount();
                                    order.setStatus(CoursesOrders.CoursesOrderStatus.YZF);//已支付
                                    order.setPayTime(LocalDateTime.now());
                                    coursesOrdersManager.updateById(order);
                                    if (memberInfo.getAllowanceAmount() > 0) {
                                        MemberAllowanceUseHistory memberAllowanceUseHistory = memberAllowanceUseHistoryService.query().eq("member_id", memberInfo.getId())
                                                .eq("use_time", order.getTakeTime().toLocalDate())
                                                .eq("meal_code", order.getMealCode()).one();
                                        if (memberAllowanceUseHistory == null) {
                                            memberAllowanceUseHistory = new MemberAllowanceUseHistory();
                                            memberAllowanceUseHistory.setAllowanceAmount(memberInfo.getMaxAllowance() - memberInfo.getAllowanceAmount());
                                            memberAllowanceUseHistory.setUseTime(order.getTakeTime().toLocalDate());
                                            memberAllowanceUseHistory.setCreateTime(LocalDateTime.now());
                                            memberAllowanceUseHistory.setMemberId(memberInfo.getId());
                                            memberAllowanceUseHistory.setMealCode(order.getMealCode());
                                            memberAllowanceUseHistory.setOrderId(order.getId());
                                            memberAllowanceUseHistoryService.saveOrUpdate(memberAllowanceUseHistory);
                                        } else {
                                            memberAllowanceUseHistory.setAllowanceAmount(memberAllowanceUseHistory.getAllowanceAmount() - memberInfo.getAllowanceAmount());
                                            memberAllowanceUseHistory.setCreateTime(LocalDateTime.now());
                                            memberAllowanceUseHistoryService.updateById(memberAllowanceUseHistory);
                                        }
                                    }
                                    if ("1".equals(memberInfo.getSchool().getPaySend())) {
                                        String url = kongxc_wx_diancan_orderServlet;
                                        url += "?orderId=" + order.getId();
                                        orderSend.sendMet(accessToken, memberInfo, order.getOrderCode(), url);
                                    }
                                    writeSuccessToBrowers("支付成功，本次消费：" + DoubleTools.doubleNumberFormat2(order.getAmount()) + ",你的余额为：【" + DoubleTools.doubleNumberFormat2(chajia) + "】", response);
                                } else {
                                    writeFailToBrowers(desc, response);
                                }
                            }
                        } else {
                            if ("没有该消费者记录".equals(responseAccount)) {
                                throw new ManagerException("你还未关联餐卡信息，请联系管理员");
                            } else {
                                throw new ManagerException(responseAccount);
                            }
                        }
                    } else {
                        writeFailToBrowers("支付失败，由于网络原因", response);
                    }
                } catch (ManagerException e) {
                    writeFailToBrowers(e.getMessage(), response);
                }
            }
            //公众号
        } else if (type.equals(CoursesOrders.PayWay.WX.toString())) {
            WxPaySendData data = new WxPaySendData();
            data.setAttach("zfcs");
            data.setBody(order.getOrderCode());
            System.out.println(memberInfo.getSchool().getCode());
            String url = diancanSchoolurlService.findByProperty("school_code", memberInfo.getSchool().getCode()).getSchoolUrl();
            url += "/weixin/notity";
            data.setNotifyUrl(url);
            data.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
            data.setOpenid(memberInfo.getOpenid());
            data.setOutTradeNo(order.getOrderCode());
            Double payMoney = order.getAmount() * 100;
            data.setTotalFee(payMoney.intValue());
            String returnXml = unifiedorderService.postReturnXml(data, request);
            try {
                Map<String, Object> mapReturn = XMLParser.getMapFromXML(returnXml);
                String return_code = (String) mapReturn.get("return_code");
                String return_msg = (String) mapReturn.get("return_msg");
                if (return_code.equalsIgnoreCase("SUCCESS")) {
                    Map<String, Object> mapToJsp = new HashMap<String, Object>();
                    String prepay_id = (String) mapReturn.get("prepay_id");
                    mapToJsp.put("appId", appID);
                    mapToJsp.put("timeStamp", Calendar.getInstance().getTimeInMillis() + "");
                    mapToJsp.put("nonceStr", RandomStringGenerator.getRandomStringByLength(32));
                    mapToJsp.put("package", "prepay_id=" + prepay_id);
                    mapToJsp.put("signType", "MD5");
                    String paySign = signature.getSign(mapToJsp);
                    mapToJsp.put("packageValue", "prepay_id=" + prepay_id);
                    mapToJsp.put("paySign", paySign);
                    mapToJsp.put("orderCode", order.getOrderCode());
                    mapToJsp.put("orderId", order.getId());
                    String jsonString = JsonUtil.getJSONString(mapToJsp);
                    for (CoursesOrdersDetails cod : detailList) {
                        cod.setOrderId(order.getId());
                        cod.setIsEffective(true);
                        coursesOrdersDetailsManager.updateById(cod);
                    }
                    System.out.println("wx支付====================");
                    System.out.println("detailList=====================" + JSONObject.toJSONString(detailList));
                    writeJson(response, jsonString);
                } else {
                    writeFailToBrowers(return_msg, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type.equals(CoursesOrders.PayWay.HTZ.toString())) {
            //现场支付
            order.setIdDelete("0");
            coursesOrdersManager.updateById(order);
            for (CoursesOrdersDetails cod : detailList) {
                cod.setOrderId(order.getId());
                cod.setIsEffective(true);
//                cod.setLastChanged(LocalDateTime.now());
                QueryWrapper<MealTime> mealTimeModel = new QueryWrapper<>();
                mealTimeModel.eq("code", cod.getMealCode());
                mealTimeModel.eq("mealType", cod.getLb());
                List<MealTime> mealTimeList = mealTimeService.list(mealTimeModel);
                if (mealTimeList != null && mealTimeList.size() > 0) {
                    cod.setQucanStartTime(mealTimeList.get(0).getQCstartTime().toString());
                    cod.setQucanEndTime(mealTimeList.get(0).getQCendTime().toString());
                }
                Courses courses = coursesService.findById(cod.getCourseId());
                coursesOrdersDetailsManager.updateById(cod);
            }
            //订单推送后台
            send = new HttpUtil(kongxc_pos_http_server_url);
            toXml = new ObjectToXML();
            String resultXml = toXml.requestCPOrderInfoKongxc(PROPASS, CUS_NAME, memberInfo.getSchool().getCode(), memberInfo, order, detailList, "0", "00", "现金");
            System.out.println(resultXml);
            try {
                send.sendToBoss(resultXml);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //-------给pos 推送 订单数据结束-------
            //小票打印
            orderReceiptPrint(detailList, order, response);
            if ("1".equals(memberInfo.getSchool().getCashSend())) {
                String url = kongxc_wx_diancan_orderServlet;
                url += "?orderId=" + order.getId();
                //--------现金支付时消息推送开始-----------
                orderSend.metXianJin(accessToken, memberInfo, order, detailList, url);
            }
            writeSuccessToBrowers("1", response);
        }
    }


    //储值卡支付
    private String payWithStoreAccount(HttpServletRequest request, MemberBaseInfo member, CoursesOrders order, List<CoursesOrdersDetails> detailList) throws ManagerException, IOException {
        //查询储值卡
        //-------给pos 推送 订单数据开始-------
        HttpUtil send2 = new HttpUtil(kongxc_pos_http_server_url);
        ObjectToXML toXml2 = new ObjectToXML();
        String resultXml = toXml2.requestCPOrderInfoKongxc(PROPASS, CUS_NAME, member.getSchool().getCode(), member, order, detailList, "0", chuzhika_num, "刷卡,储值卡");
        String responseOrderXml = null;
        try {
            responseOrderXml = send2.sendToBoss(resultXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //-------给pos 推送 订单数据结束-------
        return responseOrderXml;
    }

    //补助卡支付
    private String payWithBzAccount(HttpServletRequest request, MemberBaseInfo member, CoursesOrders order, List<CoursesOrdersDetails> detailList) throws ManagerException, IOException {
        //-------给pos 推送 订单数据开始-------
        HttpUtil send2 = new HttpUtil(kongxc_pos_http_server_url);
        ObjectToXML toXml2 = new ObjectToXML();
        String resultXml = toXml2.requestCPOrderInfoKongxc(PROPASS, CUS_NAME, member.getSchool().getCode(), member, order, detailList, "0", chuzhika_faFang, "刷卡,补助卡");
        String responseOrderXml = null;
        try {
            responseOrderXml = send2.sendToBoss(resultXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //-------给pos 推送 订单数据结束-------
        return responseOrderXml;
    }


    //补助卡储值卡混合支付
    private String payWithBzAndCzAccount(HttpServletRequest request, Double BzAmount, MemberBaseInfo member, CoursesOrders order, List<CoursesOrdersDetails> detailList) throws ManagerException, IOException {
        //-------给pos 推送 订单数据开始-------
        HttpUtil send2 = new HttpUtil(kongxc_pos_http_server_url);
        ObjectToXML toXml2 = new ObjectToXML();
        String responseOrderXml = null;
        //储值账户扣款
        String resultXml = toXml2.combinedPaymentByCreditCard(PROPASS, CUS_NAME, member.getSchool().getCode(), member, order, detailList, BzAmount / order.getAmount(), (order.getAmount() - BzAmount) / order.getAmount());
        try {
            responseOrderXml = send2.sendToBoss(resultXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //-------给pos 推送 订单数据结束-------
        return responseOrderXml;
    }

    //使用优惠账户支付
//    private String payWithAllowanceAccount(HttpServletRequest request, Double totalAmount, String cardType, MemberBaseInfo member, CoursesOrders order, List<CoursesOrdersDetails> detailList) throws ManagerException, IOException {
//        //-------给pos 推送 订单数据开始-------
//        HttpUtil send2 = new HttpUtil(kongxc_pos_http_server_url);
//        ObjectToXML toXml2 = new ObjectToXML();
//        String responseOrderXml = null;
//        String responseOrderXml2 = null;
//        try {
//            //用户储值卡支付
//            String resultXml2 = toXml2.requestOrderInfoKongxc(PROPASS, CUS_NAME, member.getSchool().getCode(), member, order, detailList, order.getAmount() / totalAmount, order.getAmount(), 0, cardType, "刷卡");
//            //公用账户生成优惠记录
//            String resultXml = toXml2.requestOrderInfoKongxc(PROPASS, CUS_NAME, member.getSchool().getCode(), member, order, detailList, member.getAllowanceAmount() / totalAmount, member.getAllowanceAmount(), 1, chuzhika_num, "优惠");
//            responseOrderXml = send2.sendToBoss(resultXml);
//            //返回值判断
//            Document doc = DocumentHelper.parseText(responseOrderXml);
//            if (doc != null) {
//                String desc = toXml2.responseDesc(responseOrderXml, request);
//                if (desc.equals("成功")) {
//                    responseOrderXml2 = send2.sendToBoss(resultXml2);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        //-------给pos 推送 订单数据结束-------
//        return responseOrderXml2;
//    }

    /**
     * pos查我的即时订单
     *
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/posTodCon", method = RequestMethod.GET)
    @ResponseBody
    public String posTodConGet(Model model, HttpServletRequest request) throws Exception {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        HttpUtil send = new HttpUtil(kongxc_pos_http_server_url);
        ObjectToXML toXml = new ObjectToXML();
        String resultXml = toXml.requestGetPosCon(PROPASS, CUS_NAME, member.getSchool().getCode(), member, LocalDateTimeUtil.format(LocalDateTime.now().minusMonths(1), "yyyy-MM-dd 00:00:00"), LocalDateTimeUtil.format(LocalDateTime.now().plusWeeks(1), "yyyy-MM-dd 23:59:59"));
        String responseRegistXml = null;
        responseRegistXml = send.sendToBoss(resultXml);
        if (StringTools.hasText(responseRegistXml)) {
            String code = toXml.resolveGetTodCon(responseRegistXml);
            if (code.equals("0000")) {
                List<OrderOfDaynut> list = toXml.resolveGetTodConDet(responseRegistXml);
                if (list != null && list.size() <= 0) {
                    model.addAttribute("content", "未查询到您POS的订单");
                }
                model.addAttribute("list", list);
            }
        }
        model.addAttribute("member", member);
        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
        return JSONObject.toJSONString(model);
    }

    /**
     * 查询选择规格时订单详情
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getLsOrderDetail2", method = RequestMethod.POST)
    @ResponseBody
    public String getLsOrderDetail2(@RequestParam String remark, String courseId, Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", member.getId());
        detailModel.ge("last_changed", LocalDate.now());
        detailModel.eq("remark", remark);
        detailModel.eq("course_id", courseId);
        CoursesOrdersDetails coursesOrdersDetails = coursesOrdersDetailsManager.getOne(detailModel, false);
        return JSONObject.toJSONString(coursesOrdersDetails);
    }


    /**
     * 我的订单
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/myOrder", method = RequestMethod.GET)
    @ResponseBody
    public String myOrderGet(@RequestParam String orderType, Model model, HttpServletRequest request, HttpServletResponse response) {

        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String openid = request.getParameter("openid");
        model.addAttribute("member", member);
        String pageNo = request.getParameter("pageNo");

        Page<CoursesOrders> courseOrderPage = new Page();
        Page<CoursesOrders> page = new Page<>();
        page.setSize(5);
        page.setCurrent(Integer.parseInt(pageNo));

        //总价
        DecimalFormat df = new DecimalFormat("#0.00");
        Double totalPrice = 0.00;
        List<CoursesOrders> coList = new ArrayList<>();
        List<CoursesOrders> wpjList = new ArrayList<>();
        if ("all".equals(orderType)) {
            //菜品订单
            QueryWrapper<CoursesOrders> cpModel = new QueryWrapper<>();
            cpModel.ne("status", CoursesOrders.CoursesOrderStatus.YYCS);
            cpModel.eq("member_id", member.getId());
            cpModel.eq("id_delete", false);
//            cpModel.orderByDesc("create_time");
//            cpModel.ge("create_time", LocalDate.now().minusDays(15));
//            cpModel.le("create_time", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
            courseOrderPage = coursesOrdersManager.queryPage(page, cpModel);
            coList = courseOrderPage.getRecords();
            for (CoursesOrders coursesOrders : coList) {
                coursesOrders.setStatusStr(coursesOrders.getStatus().getValue());
                QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
                detailModel.eq("is_effective", true);
                detailModel.eq("order_id", coursesOrders.getId());
                detailModel.gt("quantity", 0);
                detailModel.orderByDesc("last_changed");
                List<CoursesOrdersDetails> all = coursesOrdersDetailsManager.queryList(detailModel);
                for (CoursesOrdersDetails coursesOrdersDetails : all) {
                    coursesOrdersDetails.setPriceStr(df.format(coursesOrdersDetails.getPrice()));
                    totalPrice += coursesOrdersDetails.getPrice() * coursesOrdersDetails.getQuantity();
                    Courses courses = coursesOrdersDetails.getCourse();
                    //--------查询菜品主图开始----------
                    QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                    coursesImgModel.eq("course_pos_no", courses.getPosNo());
                    coursesImgModel.isNotNull("img_path");
                    coursesImgModel.isNotNull("img_url");
                    coursesImgModel.orderByDesc("mainImg");
                    List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                    courses.setCoursesImgList(coursesImgList);
                    if (coursesImgList != null && coursesImgList.size() > 0) {
                        coursesOrdersDetails.setImageMainPath(coursesImgList.get(0).getImgUrl());
                    }
                    //--------查询菜品主图结束----------
                    if (coursesOrdersDetails.getRemark() != null && !"".equals(coursesOrdersDetails.getRemark())) {
                        coursesOrdersDetails.setCourseName(courses.getNameCh() + "(" + coursesOrdersDetails.getRemark() + ")");
                        coursesOrdersDetails.setCourseNameEn(courses.getNameEn() + "(" + coursesOrdersDetails.getRemark() + ")");
                    } else {
                        coursesOrdersDetails.setCourseName(courses.getNameCh());
                        coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
                    }
                }
                coursesOrders.setDetailList(all);
                coursesOrders.setTotalPrice(df.format(totalPrice));
                totalPrice = 0.00;
            }
        } else if ("wpj".equals(orderType)) {
            //待评价(查看未评价订单)
            QueryWrapper<CoursesOrders> cpModel = new QueryWrapper<>();
//            cpModel.ne("status", CoursesOrders.CoursesOrderStatus.WZF);//除了未支付的订单
            cpModel.eq("status", CoursesOrders.CoursesOrderStatus.DDYWC);
            cpModel.eq("member_id", member.getId());
            cpModel.eq("is_comment", "0");
            cpModel.eq("id_delete", false);
//            cpModel.ge("create_time", LocalDate.now().minusDays(15));
//            cpModel.le("create_time", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
            courseOrderPage = coursesOrdersManager.queryPage(page, cpModel);
            wpjList = courseOrderPage.getRecords();
            //待评价
            for (CoursesOrders coursesOrders : wpjList) {
                coursesOrders.setStatusStr(coursesOrders.getStatus().getValue());
                QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
                detailModel.eq("is_effective", true);
                detailModel.eq("order_id", coursesOrders.getId());
                detailModel.orderByDesc("last_changed");
                List<CoursesOrdersDetails> all = coursesOrdersDetailsManager.queryList(detailModel);
                for (CoursesOrdersDetails coursesOrdersDetails : all) {
                    coursesOrdersDetails.setPriceStr(df.format(coursesOrdersDetails.getPrice()));
                    totalPrice += coursesOrdersDetails.getPrice() * coursesOrdersDetails.getQuantity();
                    Courses courses = coursesOrdersDetails.getCourse();
                    //--------查询菜品主图开始----------
                    QueryWrapper<CoursesImg> coursesImgModel = new QueryWrapper<>();
                    coursesImgModel.eq("course_pos_no", courses.getPosNo());
                    coursesImgModel.isNotNull("img_path");
                    coursesImgModel.isNotNull("img_url");
                    coursesImgModel.orderByDesc("mainImg");
                    List<CoursesImg> coursesImgList = coursesImgService.list(coursesImgModel);
                    courses.setCoursesImgList(coursesImgList);
                    if (coursesImgList != null && coursesImgList.size() > 0) {
                        coursesOrdersDetails.setImageMainPath(coursesImgList.get(0).getImgUrl());
                    }
                    //--------查询菜品主图结束----------
                    if (coursesOrdersDetails.getRemark() != null && !"".equals(coursesOrdersDetails.getRemark())) {
                        coursesOrdersDetails.setCourseName(courses.getNameCh() + "(" + coursesOrdersDetails.getRemark() + ")");
                        coursesOrdersDetails.setCourseNameEn(courses.getNameEn() + "(" + coursesOrdersDetails.getRemark() + ")");
                    } else {
                        coursesOrdersDetails.setCourseName(courses.getNameCh());
                        coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
                    }
                }
                coursesOrders.setDetailList(all);
                coursesOrders.setTotalPrice(df.format(totalPrice));
                totalPrice = 0.00;
            }

        }
        model.addAttribute("cpList", wpjList);
        model.addAttribute("coList", coList);
        model.addAttribute("totalPage", courseOrderPage.getPages());
        model.addAttribute("total", courseOrderPage.getTotal());
        model.addAttribute("pageNo", courseOrderPage.getCurrent());
//        model.addAttribute("zhOrEn", Finals.ZhOrEn.values());
//        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("result", "cpList", "coList", "totalPage", "total", "pageNo", "id", "remark", "course", "imageMainPath", "price", "quantity", "nameEn", "nameCh", "takeCode");
        return JSONObject.toJSONString(model);
    }

    /**
     * 取消订单
     *
     * @param id
     * @param model
     * @param request
     * @param response
     * @throws ManagerException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/cancel", method = RequestMethod.GET)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public String cancel(@RequestParam("id") String id, Model model) {
        CoursesOrders coursesOrders = coursesOrdersManager.getById(id);
        MemberBaseInfo memberBaseInfo = memberBaseInfoService.getById(coursesOrders.getMemberId());
        QueryWrapper<CoursesOrdersDetails> queryModel = new QueryWrapper<>();
        queryModel.eq("order_id", id);
        queryModel.eq("is_effective", true);
        List<CoursesOrdersDetails> list = coursesOrdersDetailsManager.queryList(queryModel);
        Double totalAmount = 0.0;
        for (CoursesOrdersDetails cod : list) {
            totalAmount += cod.getPrice() * cod.getQuantity();
            cod.setIsRefunding(1);
        }
        double discountAmount = totalAmount - coursesOrders.getAmount();
        coursesOrdersDetailsManager.updateBatchById(list);
        //退款
        String resultStr = restTemplate.postForObject(refundUrl.replace("CODE", coursesOrders.getOrderCode()), null, String.class);
        JSONObject result = JSONObject.parseObject(resultStr);
        if ("YES".equals(result.getString("is_success"))) {
            coursesOrders.setStatus(WCTK);
            if (coursesOrdersManager.updateById(coursesOrders)) {
                if (discountAmount > 0) {
                    MemberAllowanceUseHistory memberAllowanceUseHistory = memberAllowanceUseHistoryService.query().eq("member_id", coursesOrders.getMemberId())
                            .eq("use_time", coursesOrders.getTakeTime().toLocalDate())
                            .eq("meal_code", coursesOrders.getMealCode()).one();
                    if (memberAllowanceUseHistory != null) {
                        memberAllowanceUseHistory.setAllowanceAmount(memberAllowanceUseHistory.getAllowanceAmount() + discountAmount);
                        memberAllowanceUseHistoryService.updateById(memberAllowanceUseHistory);
                    }
                }
                //发送消息
                String accessToken = accesstokensaveService.query().one().getAccessToken();
                String url = kongxc_wx_diancan_orderServlet;
                url += "?orderId=" + coursesOrders.getId();
                //--------现金支付时消息推送开始-----------
                orderSend.tuiKunMethod(accessToken, memberBaseInfo, coursesOrders, url);
                model.addAttribute("result", "success");
            } else {
                model.addAttribute("result", "false");
            }
        } else {
            model.addAttribute("result", "false");
        }
        return JSONObject.toJSONString(model);
    }


    /**
     * 订单评价
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/common", method = RequestMethod.POST)
    public void commonPost(OrderComment com, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        CoursesOrders coursesOrders = coursesOrdersManager.findById(com.getOrderId());
        String content = com.getContent();
        com.setCreateTime(LocalDateTime.now());
        com.setScore(com.getScore() + ";" + com.getScore2() + ";" + com.getScore3());
        com.setMemberId(member.getId());
        com.setIsCheck(false);
        coursesOrders.setIsComment("1");//已评价
        coursesOrdersManager.updateById(coursesOrders);
        orderCommentService.save(com);
        String json = "{\"message\":\"success\",\"openid\":\"" + member.getOpenid() + "\"}";
        writeJson(response, json);

    }


    /**
     * 查看订单评价
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/commonView", method = RequestMethod.POST)
    @ResponseBody
    public String commonView(@RequestParam String orderId, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        CoursesOrders coursesOrder = coursesOrdersManager.getById(orderId);
        if (coursesOrder != null && coursesOrder.getIsComment().equals("1")) {
            OrderComment orderComment = orderCommentService.getByorderId(orderId);
            String score = orderComment.getScore();
            String[] split = score.split(";");
            orderComment.setScore(split[0]);
            orderComment.setScore2(split[1]);
            orderComment.setScore3(split[2]);
            model.addAttribute("result", "success");
            model.addAttribute("orderComment", orderComment);
            System.out.println(JSONObject.toJSONString(model));
            return JSONObject.toJSONString(model);
        } else {
            model.addAttribute("result", false);
            model.addAttribute("message", "系统异常");
            return JSONObject.toJSONString(model);
        }
    }


    // 调用打印机接口
    private void orderReceiptPrint(List<CoursesOrdersDetails> coursesOrdersDetailsList, CoursesOrders mainOrders, HttpServletResponse response) {
//        String data = smallTicketPrinter.queryPrinterStatus(smallTicketPrinter.SN);
        smallTicketPrinter.printOrder(coursesOrdersDetailsList, mainOrders);
    }

    //获取菜品营养
    protected Map<String, Double> getNutrient(MemberBaseInfo member) {
        QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
        detailModel.eq("is_effective", false);
        detailModel.eq("creator", member.getId());
        List<CoursesOrdersDetails> detailList = coursesOrdersDetailsManager.queryList(detailModel);

        HashMap<String, Double> hashMap = new HashMap<>();
        if (detailList == null || detailList.size() <= 0) {
            hashMap.put("能量(kcal)", 0.0);
            hashMap.put("碳水化物(g)", 0.0);
            hashMap.put("钠(mg)", 0.0);
            hashMap.put("蛋白质(g)", 0.0);
            hashMap.put("脂肪(g)", 0.0);
            return hashMap;
        }
        Map<String, Double> map = new HashMap<String, Double>();
        for (CoursesOrdersDetails coursesOrdersDetails : detailList) {
            QueryWrapper<CourseNutrition> courseNutritionModel = new QueryWrapper<>();
            Courses courses = coursesService.findById(coursesOrdersDetails.getCourseId());

            if (courses != null) {
                courseNutritionModel.eq("recipes_code", courses.getPosNo());
                coursesOrdersDetails.setCourseName(courses.getNameCh());
                if (!StringTools.hasText(courses.getNameEn())) {
                    coursesOrdersDetails.setCourseNameEn(courses.getNameCh());
                } else {
                    coursesOrdersDetails.setCourseNameEn(courses.getNameEn());
                }
            }

            courseNutritionModel.eq("is_delete", false);
            List<CourseNutrition> courseNutrition = courseNutritionService.list(courseNutritionModel);
            for (CourseNutrition courseNutrition2 : courseNutrition) {
                if (map.containsKey(courseNutrition2.getNutritionCode())) {
                    Double temVal = map.get(courseNutrition2.getNutritionCode());
                    temVal += courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), temVal);
                } else {
                    Double val = courseNutrition2.getQuantity() * coursesOrdersDetails.getQuantity();
                    map.put(courseNutrition2.getNutritionCode(), val);
                }
            }
        }

        if (Finals.ZhOrEn.Z.equals(member.getZhOrEn())) {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("能量(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("碳水化物(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("钠(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("蛋白质(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("脂肪(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        } else {
            for (String key : map.keySet()) {
                if (Finals.NUT_CODE_NL.equals(key)) {
                    hashMap.put("Energy(kcal)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_TSHHW.equals(key)) {
                    hashMap.put("Carbohydrate(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_SSXW.equals(key)) {
                    hashMap.put("Na(mg)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_DBZ.equals(key)) {
                    hashMap.put("Protein(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
                if (Finals.NUT_CODE_ZF.equals(key)) {
                    hashMap.put("Fat(g)", DoubleTools.doubleNumberFormat2(map.get(key)));
                }
            }
        }
        return hashMap;
    }


    /**
     * 向请求方发送json字符串
     *
     * @param response
     * @throws IOException
     */
    protected void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setHeader("ContentType", "text/json");
        response.setHeader("Content-Type", "text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(obj);
        out.close();
    }


    @GetMapping("/weChatPayResult")
    @ResponseBody
    public void weChatPayResult(@RequestParam("orderId") String orderId, @RequestParam("message") String message) {
//        主单
        CoursesOrders coursesOrders = coursesOrdersManager.getById(orderId);
        System.out.println("coursesOrders------" + coursesOrders);
//        细单
        List<CoursesOrdersDetails> coursesOrdersDetailsList = coursesOrdersDetailsManager.findByProperty("order_id", orderId);
        System.out.println("coursesOrdersDetailsList------" + coursesOrdersDetailsList);
        if ("get_brand_wcpay_request:cancel".equals(message) || "get_brand_wcpay_request:fail".equals(message)) {
            for (CoursesOrdersDetails coursesOrdersDetails : coursesOrdersDetailsList) {
                coursesOrdersDetails.setIsEffective(false);
            }
        }
        coursesOrdersDetailsManager.updateBatchById(coursesOrdersDetailsList);
    }


    @GetMapping("/getById")
    @ResponseBody
    public String getById(Model model, @RequestParam("orderId") String orderId, HttpServletRequest request, HttpServletResponse response) {
//        主单
        CoursesOrders coursesOrders = coursesOrdersManager.getById(orderId);
//        细单
        List<CoursesOrdersDetails> coursesOrdersDetailsList = coursesOrdersDetailsManager.findByProperty("order_id", orderId);
        for (CoursesOrdersDetails coursesOrdersDetails : coursesOrdersDetailsList) {
            //--------查询菜品主图开始----------
            List<CoursesImg> coursesImgList = coursesImgService.query()
                    .eq("course_pos_no", coursesOrdersDetails.getCourse().getPosNo())
                    .isNotNull("img_path")
                    .isNotNull("img_url")
                    .eq("mainImg", 1)
                    .orderByDesc("last_changed_time").list();
            if (coursesImgList.size() > 0) {
                coursesOrdersDetails.setImageMainPath(coursesImgList.get(0).getImgUrl());
            }
            //--------查询菜品主图结束----------
        }
        model.addAttribute("result", "success");
        model.addAttribute("coursesOrders", coursesOrders);

        ReceiveAddress address = coursesOrders.getAddress();
        address.setName(coursesOrders.getPayMemberName());
        if ("3".equals(coursesOrders.getTakeMealType()) && coursesOrders.getAddress() != null) {
            address.setTel(address.getTel());
        } else {
            address.setTel(coursesOrdersDetailsList.get(0).getCreatorInfo().getMobile());
        }
        address.setArchitecture(coursesOrders.getArchitecture());
        address.setAddress(coursesOrders.getAddressDetail());
        coursesOrders.setAddress(address);
        model.addAttribute("coursesOrdersDetailsList", coursesOrdersDetailsList);
//        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("result", "takeMealType", "takeTime", "orderCode", "coursesOrders", "coursesOrdersDetailsList", "amount", "createTime", "id", "remark", "course", "imageMainPath", "price", "quantity", "nameEn", "nameCh", "takeCode", "mealCode");
        return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
    }

    @GetMapping("/getByCode")
    @ResponseBody
    public String getByCode(Model model, @RequestParam("orderCode") String orderCode, HttpServletRequest request, HttpServletResponse response) {
//        主单
        String status = request.getParameter("status");
        if (StringUtils.isEmpty(status)) {
            status = "BCZ";
        }
        CoursesOrders coursesOrders = coursesOrdersManager.getOne(new QueryWrapper<CoursesOrders>().eq("order_code", orderCode).eq("status", status), false);
        if (coursesOrders == null) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "未查询到可核销订单");
            return JSONObject.toJSONString(model, SerializerFeature.WriteMapNullValue);
        }
        coursesOrders = autoMapper.mapperEntity(coursesOrders);
        coursesOrders.setStatusStr(coursesOrders.getStatus().getValue());
//        细单
        List<CoursesOrdersDetails> coursesOrdersDetailsList = coursesOrdersDetailsManager.findByProperty("order_id", coursesOrders.getId());
        double totalAmount = coursesOrdersDetailsList.stream().mapToDouble(i -> i.getPrice() * i.getQuantity()).sum();
        model.addAttribute("result", "success");
        model.addAttribute("orderId", coursesOrders.getId());
        model.addAttribute("mealTime", coursesOrdersDetailsList.get(0).getMealName());

        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("allowanceAmount", totalAmount - coursesOrders.getAmount());
        model.addAttribute("amount", coursesOrders.getAmount());

        model.addAttribute("customerNo", coursesOrdersDetailsList.get(0).getCreatorInfo().getIdNumber());
        model.addAttribute("takeTime", coursesOrders.getTakeTime());
        model.addAttribute("createTime", coursesOrders.getCreateTime());
        model.addAttribute("customerName", coursesOrders.getPayMemberName());
        if ("3".equals(coursesOrders.getTakeMealType()) && coursesOrders.getAddress() != null) {
            model.addAttribute("customerMobile", coursesOrders.getAddress().getTel());
        } else {
            model.addAttribute("customerMobile", coursesOrdersDetailsList.get(0).getCreatorInfo().getMobile());
        }
        model.addAttribute("payType", coursesOrders.getPayWay().getValue());
        model.addAttribute("coursesOrdersDetailsList", coursesOrdersDetailsList);
//        SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
        return JSONObject.toJSONStringWithDateFormat(model, "yyyy-MM-dd");
    }

    @GetMapping("/upOrderStatus")
    @ResponseBody
    public String upOrderStatus(Model model, @RequestParam("orderCode") String orderCode, @RequestParam("status") String status) {
        UpdateWrapper<CoursesOrders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_code", orderCode);
        updateWrapper.ne("status", status);
        updateWrapper.set("status", status);
        if (coursesOrdersManager.update(updateWrapper)) {
            if ("BCWC".equals(status)) {
                CoursesOrders coursesOrders = coursesOrdersManager.getOne(new QueryWrapper<CoursesOrders>().eq("order_code", orderCode).eq("status", status), false);
                //发送取餐通知
                String url = kongxc_wx_diancan_orderServlet;
                url += "?orderId=" + coursesOrders.getId();
                orderSend.quCanMethod(accesstokensaveService.getOne(new QueryWrapper<>(), false).getAccessToken(), memberBaseInfoService.getById(coursesOrders.getMemberId()), coursesOrders, url);
            }
            model.addAttribute("result", "success");
            model.addAttribute("message", "更新成功");
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "更新失败");
        }
        return JSONObject.toJSONString(model);
    }

    @GetMapping("/orderWriteOff")
    @ResponseBody
    public String orderWriteOff(Model model, @RequestParam("orderId") String orderId) {
        CoursesOrders coursesOrders = coursesOrdersManager.getById(orderId);
        coursesOrders.setStatus(DDYWC);
        coursesOrders.setCompletedTime(LocalDateTime.now());
        if (coursesOrdersManager.updateById(coursesOrders)) {
            model.addAttribute("result", "success");
            model.addAttribute("message", "订单核销成功");
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "订单核销失败");
        }
        return JSONObject.toJSONString(model);
    }
}
